/*
 *  Copyright 2001-2004 The Apache Software Foundation
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package ar.uba.fi.posgrado.academy.web.action.course;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import ar.uba.fi.posgrado.academy.model.Course;
import ar.uba.fi.posgrado.academy.model.Instalment;
import ar.uba.fi.posgrado.academy.service.CourseService;
import ar.uba.fi.posgrado.academy.service.InstalmentService;
import ar.uba.fi.posgrado.common.exception.PosgradoException;
import ar.uba.fi.posgrado.common.exception.RepeatedNameException;
import ar.uba.fi.posgrado.economy.service.DebtService;

/**
 * Action que modifica las {@link Instalment cuotas} de un {@link Course curso}.<br>
 * 
 * @author ariel.piechotka
 */
public class ModifyInstalmentsAction extends Action {
	/** Logger */
	private static Logger logger = Logger
			.getLogger(ModifyInstalmentsAction.class);

	private CourseService courseService;

	private InstalmentService instalmentService;

	private DebtService debtService;

	public void setCourseService(CourseService courseService) {
		this.courseService = courseService;
	}

	public void setInstalmentService(InstalmentService instalmentService) {
		this.instalmentService = instalmentService;
	}

	public void setDebtService(DebtService debtService) {
		this.debtService = debtService;
	}

	/**
	 * @see org.apache.struts.action.Action#execute(org.apache.struts.action.ActionMapping,
	 *      org.apache.struts.action.ActionForm,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		if (logger.isDebugEnabled())
			logger.debug("Por modificar cuotas...");

		Course course = courseService.getById(Long.parseLong(request
				.getParameter("courseId")));
		String registrationFeeValueStr = request
				.getParameter("registrationFeeValue");
		String instalmentsStr = request.getParameter("instalments");
		String qtyRegistrationFees = request.getParameter("registrationFeeQty");

		double registrationFeeValue = registrationFeeValueStr.trim().equals("") ? 0.0
				: Double.parseDouble(registrationFeeValueStr);
		List<Double> instalmentsValues = new ArrayList<Double>();
		if (!instalmentsStr.trim().equals(""))
			for (String instalmentStr : instalmentsStr.split(";"))
				instalmentsValues.add(Double.parseDouble(instalmentStr));

		Set<Instalment> instalments = course.getInstalments();
		for (Instalment instalment : instalments)
			instalmentService.delete(instalment);
		instalments.clear();

		if (registrationFeeValue > 0.0) {
			Instalment registrationFee = createInstalment(request
					.getParameter("debtTypeSelectedRegFee"), course, 0,
					registrationFeeValue);
			course.setQtyRegistrationFees(Byte.parseByte(qtyRegistrationFees));
			instalments.add(registrationFee);
		}
		else
			course.setQtyRegistrationFees((byte)0);

		int i = 1;
		for (Double instalmentValue : instalmentsValues) {
			Instalment instalment = createInstalment(request
					.getParameter("debtTypeSelectedInst"), course, i++,
					instalmentValue);
			instalments.add(instalment);
		}

		try {
			course = courseService.update(course);
		} catch (RepeatedNameException e) {
			logger.info(e.getMessage());
			ActionMessages errors = new ActionMessages();
			errors.add("course.code", new ActionMessage(e.getMessage(), false));
			saveErrors(request, errors);
			return mapping.getInputForward();
		}

		logger.info("Modificar cuotas finalizado");
		return mapping.findForward("success");
	}

	private Instalment createInstalment(String debtTypeId, Course course,
			int instNumber, double registrationFeeValue)
			throws PosgradoException {
		Instalment registrationFee = new Instalment();
		registrationFee.setInstNumber(instNumber);
		Long debtType = Long.parseLong(debtTypeId);
		registrationFee.setDebtType(debtService.getDebtTypeById(debtType));
		registrationFee.setValue(registrationFeeValue);
		registrationFee.setCourse(course);
		instalmentService.create(registrationFee);
		return registrationFee;
	}
}
